package com.qianniu.napi.admin.service.akka;

import akka.actor.UntypedActor;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.*;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FenxiaoActor extends UntypedActor {

    private final static Logger logger = LoggerFactory.getLogger(FenxiaoActor.class);
    private INewsService newsService = (INewsService) SpringUtil.getBean("newsServiceImpl");
    private IOrderService orderService = (IOrderService) SpringUtil.getBean("orderServiceImpl");
    private IRedisService redisService = (IRedisService) SpringUtil.getBean("redisServiceImpl");
    private IFensService fensService = (IFensService) SpringUtil.getBean("fensServiceImpl");
    private IUserService userService = (IUserService) SpringUtil.getBean("userServiceImpl");
    private IFenxiaoService fenxiaoService = (IFenxiaoService) SpringUtil.getBean("fenxiaoServiceImpl");
    private IFenxiaoFanService fenxiaoFanService = (IFenxiaoFanService) SpringUtil.getBean("fenxiaoFanServiceImpl");
    private IJifenService jifenService = (IJifenService) SpringUtil.getBean("jifenServiceImpl");
    private IXnbiService xnbiService = (IXnbiService) SpringUtil.getBean("xnbiServiceImpl");
    private IAccountService accountService = (IAccountService) SpringUtil.getBean("accountServiceImpl");
    private IQnpay qnpay = (IQnpay) SpringUtil.getBean("qnpayImpl");
    private IMaccountService maccountService = (IMaccountService) SpringUtil.getBean("maccountServiceImpl");


    @Override
    public void onReceive(Object message) {

        if (message instanceof String) {
            String msg = message.toString();
            logger.debug(">>>>>> FenxiaoActor receive message:" + msg);

            // 格式 oid+mpid
            String[] arr = msg.split("@");
            if (arr.length < 2) return;

            String type = arr[0];
            String oid = arr[1];
            if (type == null || oid.equals("null")) {
                return;
            }

            if (Strings.isNullOrEmpty(oid)) {
                return;
            }

            Order order = orderService.selectById(oid);

            if (type.equals(Constants.AKKA_MSG_ORDER_FENXIAO_XIAOFEI)) {

                xfFenxiaoFan(order);
            } else if (type.equals(Constants.AKKA_MSG_ORDER_FENXIAO_HUIYUAN)) {
//                fxXiaofeiFan(order);
            }

        }
    }


    /*
     * 计算分销额
     * 分销计算原则
     * 1.会员|代理人才有分销权利，普通用户没有
     * 2.普通用户对单个商品分享只能享受商品直推推广分佣（详见方法：shareFan）
     * 3.锁客（锁粉）模式下，上下级关系不变
     * 4.非锁客（锁粉）模式，粉丝变会员之前
     * 5.计算分销额，区别会员商品+普通商品
     * 6.会员商品直接单独购买，不能多商品组合订单
     * 7.普通商品可以组合订单(第一期分销只做总订单分销)
     * 8.第一期分销只做返现金
     * 9.分销价格计算依赖商品实际支付价格
     * 10.上级返佣人，必须是会员才能拥有分佣资格
     * 11.绩效极差奖励暂未支持
     */
    public void xfFenxiaoFan(Order order) {
        logger.info("------------------------------------------------------start to xffenxiaofan");

        //返现用户
        User user = null;
        Long mpid = order.getMpid();
        Long uid = order.getUid();

        Fenxiao fenxiao = fenxiaoService.selectOne(new EntityWrapper<Fenxiao>().eq("mpid", mpid));
        MerchantConfig mconfig = redisService.getMconfig(mpid);

        List<FenxiaoFan> fxflist = fenxiaoFanService.selectList(new EntityWrapper<FenxiaoFan>().eq("mpid", mpid).orderBy("mlevel", true));

        if (fenxiao == null) {
            logger.debug("------------------------------------------------------xffenxiaofan is null for mpid=" + mpid);
            return;
        }
        if (fxflist == null || fxflist.size() == 0) {
            logger.debug("------------------------------------------------------fxflist is null for mpid=" + mpid);
            return;
        }

//        if (fxflist.size() != fenxiao.getFxlevel()) {
//            logger.debug("------------------------------------------------------fxflist.size ne fenxiao.getFxlevel for mpid=" + mpid);
//            return;
//        }
        logger.info("------------------------------------------------------start to come Fenxiao jisuan");

        Map<String, FenxiaoFan> fxmap = new HashMap<String, FenxiaoFan>();
        for (FenxiaoFan item : fxflist) {
            fxmap.put("mlevel_" + item.getHytype() + "_" + item.getMlevel(), item);
        }
        logger.info("------------------------------------------start to come Fenxiao fxmap=" + fxmap);

        if(fenxiao.getXffantype()==null) return;

        int fxlevel = fenxiao.getFxlevel();
        Map<String, User> fxusermap = new HashMap<String, User>();
        Map<String, BigDecimal> fxemap = new HashMap<String, BigDecimal>();
        FenxiaoFan fxfan = null;
        int level = 0;

        BigDecimal jiandian = fenxiao.getJiandian();//见点奖励等效 培训费奖励

        for (int i = 1; i <= fxlevel; i++) {

            Fens fens = fensService.selectOne(new EntityWrapper<Fens>()
                    .eq("uid", uid)            //当前成交用户
                    .eq("level_type", i)      //级别
                    .eq("state", 1)  //* 10.必须有效
            );

            if (fens == null) {
                logger.info("------------------------------------------fxXiaofeiFan continue for fens is null for level_type=" + i);
                continue;
            }

            user = userService.selectById(fens.getPuid());
            if (user == null || user.getState() != 1) {
                logger.info("------------------------------------------fxXiaofeiFan continue for puser is null or state=1 for fens.getPuid()=" + fens.getPuid());
                continue;
            }
            if (user.getIsMember() != 1 && user.getIsAgent() != 1) {
                logger.info("------------------------------------------fxXiaofeiFan continue for user.getIsMember()!=1&&user.getIsAgent()!=1");
                continue;
            }

            //======待完善
            //======如果上级会员中途失效，如何处理
            //======会员升级一般会有见点奖励，特定级别首领有
            level = user.getMemberLevel();

            logger.info("-------------------------------------------xffenxiaofan huiyuan order.getType()=" + order.getType() + " level=" + level);

            String key = "mlevel_" + user.getUtype() + "_" + level;
            logger.info("------------------------------------------------------xffenxiaofan key=" + key);

            // 系统暂时支持会员级别
            fxfan = fxmap.get(key);//会员对应级别
            logger.info("---------------------------------------------------------------------------xffenxiaofan fxfan from fxmap.get(key)=" + fxfan);
            if (fxfan == null) continue;//非会员 不参与分销
            logger.info("------------------------------------------------------start to come xffenxiaofan huiyuan order=" + order);

            //普通商品消费，按照普通商品比例提成
            logger.info("----------------------------------------------------------------------------------------------------fxfan=" + fxfan);
            if (i == 1 && fxfan.getXffan1() != null) {
                logger.info("-------------------------------------------fxfan setFxe1 order.getRealpay()=" + order.getRealpay());
                logger.info("-------------------------------------------fxfan setFxe1 fxfan.getXffan1()=" + fxfan.getXffan1());
                order.setFxe1(order.getRealpay().multiply(BigDecimal.valueOf(fxfan.getXffan1())).divide(new BigDecimal(100)));//实际支付金额*返点比例
                logger.info("-------------------------------------------fxfan setFxe1 order.getFxe1()=" + order.getFxe1());
//              消费订单分销奖励 二期通过扩展商品表格 实现独立控制每个商品的奖励计算
//                 if (ogods != null && ogods.size() > 0) {
//                       for (int y = 0; y < ogods.size(); y++) {
//                           OrderGoods ogood = ogods.get(y);
//                           ogood.setFxe1(ogood.getSaleprice().multiply(new BigDecimal(ogood.getNumber())).multiply(BigDecimal.valueOf(fxfan.getXffan1())));
//                       }
//                   }
            } else if (i == 2 && fxfan.getXffan2() != null) {
                order.setFxe2(order.getRealpay().multiply(BigDecimal.valueOf(fxfan.getXffan2())).divide(new BigDecimal(100)));//实际支付金额*返点比例
//                   if (ogods != null && ogods.size() > 0) {
//                       for (int y = 0; y < ogods.size(); y++) {
//                           OrderGoods ogood = ogods.get(y);
//                           ogood.setFxe2(ogood.getSaleprice().multiply(new BigDecimal(ogood.getNumber())).multiply(BigDecimal.valueOf(fxfan.getXffan2())));
//                       }
//                   }
            } else if (i == 3 && fxfan.getXffan3() != null) {
                order.setFxe3(order.getRealpay().multiply(BigDecimal.valueOf(fxfan.getXffan3())).divide(new BigDecimal(100)));//实际支付金额*返点比例
//                   if (ogods != null && ogods.size() > 0) {
//                       for (int y = 0; y < ogods.size(); y++) {
//                           OrderGoods ogood = ogods.get(y);
//                           ogood.setFxe3(ogood.getSaleprice().multiply(new BigDecimal(ogood.getNumber())).multiply(BigDecimal.valueOf(fxfan.getXffan3())));
//                       }
//                   }
            } else if (i == 4 && fxfan.getXffan4() != null) {
                order.setFxe4(order.getRealpay().multiply(BigDecimal.valueOf(fxfan.getXffan4())).divide(new BigDecimal(100)));//实际支付金额*返点比例
//                   if (ogods != null && ogods.size() > 0) {
//                       for (int y = 0; y < ogods.size(); y++) {
//                           OrderGoods ogood = ogods.get(y);
//                           ogood.setFxe4(ogood.getSaleprice().multiply(new BigDecimal(ogood.getNumber())).multiply(BigDecimal.valueOf(fxfan.getXffan4())));
//                       }
//                   }
            } else if (i == 5 && fxfan.getXffan5() != null) {
                order.setFxe5(order.getRealpay().multiply(BigDecimal.valueOf(fxfan.getXffan5())).divide(new BigDecimal(100)));//实际支付金额*返点比例
//                   if (ogods != null && ogods.size() > 0) {
//                       for (int y = 0; y < ogods.size(); y++) {
//                           OrderGoods ogood = ogods.get(y);
//                           ogood.setFxe5(ogood.getSaleprice().multiply(new BigDecimal(ogood.getNumber())).multiply(BigDecimal.valueOf(fxfan.getXffan5())));
//                       }
//                   }
            } else if (i == 6 && fxfan.getXffan6() != null) {
                order.setFxe6(order.getRealpay().multiply(BigDecimal.valueOf(fxfan.getXffan6())).divide(new BigDecimal(100)));//实际支付金额*返点比例
//                   if (ogods != null && ogods.size() > 0) {
//                       for (int y = 0; y < ogods.size(); y++) {
//                           OrderGoods ogood = ogods.get(y);
//                           ogood.setFxe6(ogood.getSaleprice().multiply(new BigDecimal(ogood.getNumber())).multiply(BigDecimal.valueOf(fxfan.getXffan6())));
//                       }
//                   }
            } else if (i == 7 && fxfan.getXffan7() != null) {
                order.setFxe7(order.getRealpay().multiply(BigDecimal.valueOf(fxfan.getXffan7())).divide(new BigDecimal(100)));//实际支付金额*返点比例
//                   if (ogods != null && ogods.size() > 0) {
//                       for (int y = 0; y < ogods.size(); y++) {
//                           OrderGoods ogood = ogods.get(y);
//                           ogood.setFxe7(ogood.getSaleprice().multiply(new BigDecimal(ogood.getNumber())).multiply(BigDecimal.valueOf(fxfan.getXffan7())));
//                       }
//                   }
            }


            //被奖励人
            fxusermap.put("fxuser" + i, user);
            logger.info("-----------------------------------------------------xffenxiaofan fxuser=" + user);

            if (i == 1 && order.getFxe1() != null && order.getFxe1().doubleValue() > 0) {
                fxemap.put("fxe" + i, order.getFxe1());
            } else if (i == 2 && order.getFxe2() != null && order.getFxe2().doubleValue() > 0)
                fxemap.put("fxe" + i, order.getFxe2());
            else if (i == 3 && order.getFxe3() != null && order.getFxe3().doubleValue() > 0)
                fxemap.put("fxe" + i, order.getFxe3());
            else if (i == 4 && order.getFxe4() != null && order.getFxe4().doubleValue() > 0)
                fxemap.put("fxe" + i, order.getFxe4());
            else if (i == 5 && order.getFxe5() != null && order.getFxe5().doubleValue() > 0)
                fxemap.put("fxe" + i, order.getFxe5());
            else if (i == 6 && order.getFxe6() != null && order.getFxe6().doubleValue() > 0)
                fxemap.put("fxe" + i, order.getFxe6());
            else if (i == 7 && order.getFxe7() != null && order.getFxe7().doubleValue() > 0)
                fxemap.put("fxe" + i, order.getFxe7());

        }

        logger.info("---------------------------------------------------xffenxiaofan for over");

        if (order.getFantimeType() == null) order.setFantimeType(mconfig.getFantimeType());
        order.updateById();

        //===待完善
//       if (ogods != null && ogods.size() > 0) {
//           for (int y = 0; y < ogods.size(); y++) {
//               OrderGoods ogood = ogods.get(y);
//               ogood.updateById();
//           }
//       }

        boolean ruzhang = mconfig.getFantimeType() == FantimeType.payok.getVal();
        boolean nowfan = mconfig.getIsAutofan() == 1 && ruzhang;

        logger.info("----------------------------------------------------xffenxiaofan fanyong foreach");
        for (int i = 1; i <= fenxiao.getFxlevel(); i++) {

            BigDecimal fxe = fxemap.get("fxe" + i);
            User fxuser = fxusermap.get("fxuser" + i);
            logger.info("----------------------------------------------------xffenxiaofan fxe=" + fxe);
            if (fxuser == null) continue;

            fanyong(fxuser, fxe, fenxiao.getXffantype(), FantimeType.payok.getVal(), order, ruzhang, nowfan, XftypeEnum.fenxiaofan);
        }

        logger.info("----------------------------------------------------xffenxiaofan over");
    }

    //返佣金入账（都是首次）
    //返币 返积分 返优惠券 没有待入账一说
    private void fanyong(User user, BigDecimal fxe, Integer fantype, Integer fantime, Order order, Boolean ruzhang, Boolean nowfan, XftypeEnum xftypeEnum) {

        Map<String, Object> paymap = new HashMap<String, Object>();
        MerchantApp mapp = redisService.getMApp(user.getMpid());
        if (fantype == XffanType.qian.getVal()) {
            //现金很特殊，区分不同时刻返佣金，先入账
            //商家出账记录，对于商家发生实际现金变动时，才会生成记录
            addAccountFlow(user, fxe, ruzhang, fantime, order, IotypeEnum.input, xftypeEnum);
            if (nowfan) {
                paymap = qnpay.payPakect(user.getMpid(), mapp.getAppid(), user, fxe, "佣金奖励", "127.0.0.1");
                if (paymap.containsKey("result_code") && paymap.get("result_code").toString().equals("SUCCESS")) {
                    //秒到账成功
                    addMaccountFlow(user, fxe, order.getOrderNo(), IotypeEnum.output, xftypeEnum, order.getTransactionId());
                    //奖励佣金直接发放
                    addAccountAutoFanFlow(user, fxe, fantime, order, IotypeEnum.output, xftypeEnum.autofanli, paymap.get("payment_no").toString());
                }
            }
        } else if (fantype == XffanType.quan.getVal() && nowfan) {//返券
            //待完善

        } else if (fantype == XffanType.xnbi.getVal() && nowfan) {//返币
            addXnbiFlow(user, fxe, ruzhang, fantime, order.getOrderNo(), IotypeEnum.input, xftypeEnum, xftypeEnum.getName());
        } else if (fantype == XffanType.jifen.getVal() && nowfan) {
            //返积分
            addJifenFlow(user, fxe, ruzhang, fantime, order.getOrderNo(), IotypeEnum.input, JftypeEnum.share, xftypeEnum.getName());
        }

    }


    //自动发放佣金，不走总账户
    //总账户不增加，可用账户不增加，累计佣金增加
    private void addAccountAutoFanFlow(User user, BigDecimal money, Integer fantimeType,
                                       Order order, IotypeEnum iotype, XftypeEnum xftype, String paymentno) {
        Long uid = user.getId();
        Long mid = user.getMid();
        Long mpid = user.getMpid();

        //付款失败，进入待转账流水
        AccountFlow af = new AccountFlow();
        af.setAmount(new BigDecimal(0));
        af.setDikou(new BigDecimal(0));
        af.setRealpay(money);//实际提现
        af.setTotal(money);

        Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
        if (act == null) {
            act = accountService.initAccount(uid, mid, mpid);
        }
        User ruser = userService.selectById(uid);
        af.setNickname(ruser != null ? ruser.getNickName() : null);
        af.setHeadimg(ruser != null ? ruser.getAvatarPic() : null);
        af.setPhone(ruser != null ? ruser.getPhone() : order.getPhone());

        af.setSn(order.getOrderNo());
        af.setTransactionid(paymentno);
        af.setIotype(iotype.getVal());//个人账户出账
        af.setXftype(xftype.getVal());//消费类型
        af.setXftypename(xftype.getName());//消费类型
        af.setFantimeType(fantimeType);//个人消费

        af.setState(1);
        af.setIsConfirm(-1);
        af.setRuzhang(0);
        af.setTradetime(new Date());
        af.setCreatetime(af.getTradetime());
        af.setRemark(xftype.getName());

        af.setUid(uid);
        af.setMid(mid);
        af.setMpid(mpid);
        af.setSid(order.getSid());
        af.setLeagueid(order.getLeagueid());
        af.setLasttotal(act.getTotal());
        af.setLastamount(act.getAmount());
        af.insert();

        Boolean flag = false;
        Account naccount = new Account();
        while (!flag) {
            act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
            Long version = act.getVersion();
            BigDecimal fanli = act.getFanli();

            naccount.setFanli(fanli.add(af.getRealpay()));

            naccount.setModifytime(new Date());
            naccount.setModifier(uid);
            naccount.setVersion(version + 1);

            af.setIsConfirm(1);
            af.setRuzhang(0);//只有延时佣金【需要核销或者需要确认订单的】才有 ruzhang=1
            af.setConfirmDate(new Date());
            af.setLasttotal(act.getTotal());
            af.setLastamount(act.getAmount());
            flag = accountService.update(naccount, new EntityWrapper<Account>().eq("uid", uid).eq("version", version));
            if (flag) af.updateById();
        }
    }


    private void addMaccountFlow(User user, BigDecimal money,
                                 String sn, IotypeEnum iotype, XftypeEnum xftype, String transactionId) {
        Long uid = user.getId();
        Long mid = user.getMid();
        Long mpid = user.getMpid();

        //付款失败，进入待转账流水
        MaccountFlow maf = new MaccountFlow();
        maf.setAmount(money);//实付100剩余20在一次充值时已更新
        maf.setMamount(new BigDecimal(0));//各种抵扣额度=商家的营销费用=总营销金额130

        maf.setUid(uid);
        maf.setMid(mid);
        maf.setMpid(mpid);

        maf.setCreatetime(new Date());
        maf.setTradetime(new Date());
        maf.setState(1);
        maf.setIsConfirm(-1);

        maf.setIotype(iotype.getVal());
        maf.setXftype(xftype.getVal());

        maf.setRemark(xftype.getName());
        maf.setSn(sn);
        maf.setTransactionid(transactionId);
        maf.insert();

        boolean flag = false;

        Maccount maccount = new Maccount();//企业付款成功
        while (!flag) {
            Maccount ma = maccountService.selectOne(new EntityWrapper<Maccount>().eq("mid", mid));
            if (ma == null) {
                ma = maccountService.initMaccount(uid, mid);
            }

            Long version = ma.getVersion();
            BigDecimal amount = ma.getAmount();
            BigDecimal total = ma.getTotal();
            BigDecimal sale = ma.getSaleAmount();
            BigDecimal market = ma.getMamount();

            maccount.setTotal(iotype.getVal() == -1 ? total.subtract(maf.getAmount()) : total.add(maf.getAmount()));       //总金额
            if (iotype.getVal() == 1) maccount.setSaleAmount(sale.add(maf.getAmount()));//累计销售额度
            maccount.setAmount(iotype.getVal() == -1 ? amount.subtract(maf.getAmount()) : amount.add(maf.getAmount()));    //可用余额
            maccount.setMamount(iotype.getVal() == -1 ? market.subtract(maf.getMamount()) : market.add(maf.getMamount()));  //营销总金额

            maccount.setModifytime(new Date());
            maccount.setModifier(uid);
            maccount.setVersion(version + 1);

            maf.setIsConfirm(1);
            maf.setLasttotal(ma.getTotal());
            maf.setConfirmDate(new Date());

            flag = maccountService.update(maccount, new EntityWrapper<Maccount>().eq("id", ma.getId()).eq("version", version));
            if (flag) maf.insertOrUpdate();
            logger.info("===========maccount flag=" + flag);
        }
    }

    //返佣流水,iotype==1
    private void addAccountFlow(User user, BigDecimal money, Boolean ruzhang, Integer fantimeType,
                                Order order, IotypeEnum iotype, XftypeEnum xftype) {
        Long uid = user.getId();
        Long mid = user.getMid();
        Long mpid = user.getMpid();

        //付款失败，进入待转账流水
        AccountFlow af = new AccountFlow();
        af.setAmount(money);
        af.setDikou(new BigDecimal(0));//总营销金额 130
        af.setRealpay(new BigDecimal(0));//总价200 实付100
        af.setTotal(af.getAmount());

        Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
        if (act == null) {
            act = accountService.initAccount(uid, mid, mpid);
        }
        User ruser = userService.selectById(uid);
        af.setNickname(ruser != null ? ruser.getNickName() : null);
        af.setHeadimg(ruser != null ? ruser.getAvatarPic() : null);
        af.setPhone(ruser != null ? ruser.getPhone() : null);

        af.setSn(order.getOrderNo());
        af.setTransactionid(order.getTransactionId());
        af.setIotype(iotype.getVal());//个人账户出账
        af.setXftype(xftype.getVal());//消费类型
        af.setFantimeType(fantimeType);//个人消费

        af.setIsConfirm(-1);
        af.setRuzhang(-1);
        af.setState(1);
        af.setTradetime(new Date());
        af.setCreatetime(new Date());
        af.setRemark(xftype.getName());
        af.setUid(uid);
        af.setMid(mid);
        af.setMpid(mpid);

        af.setSid(order.getSid());
        af.setLeagueid(order.getLeagueid());
        af.setLasttotal(act.getTotal());
        af.setLastamount(act.getAmount());
        af.insert();

        Boolean flag = false;
        Account naccount = new Account();
        while (!flag) {

            act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
            af.setIsConfirm(1);
            af.setLasttotal(act.getTotal());
            af.setLastamount(act.getAmount());
            af.setConfirmDate(new Date());

            Long version = act.getVersion();

            BigDecimal total = act.getTotal();
            BigDecimal amount = act.getAmount();

            BigDecimal unuseAmount = act.getUnuseAmount();
            BigDecimal fanliing = act.getFanliing();

            naccount.setTotal(iotype.getVal() == 1 ? total.add(af.getAmount()) : total.subtract(af.getAmount()));

            if (ruzhang) {
                af.setRuzhang(1);
                naccount.setAmount(iotype.getVal() == 1 ? amount.add(af.getAmount()) : amount.subtract(af.getAmount()));
            } else {
                naccount.setFanliing(iotype.getVal() == 1 ? fanliing.add(af.getAmount()) : fanliing.subtract(af.getAmount()));
                naccount.setUnuseAmount(iotype.getVal() == 1 ? unuseAmount.add(af.getAmount()) : unuseAmount);
            }
            naccount.setModifytime(new Date());
            naccount.setModifier(uid);
            naccount.setVersion(version + 1);

            flag = accountService.update(naccount, new EntityWrapper<Account>().eq("uid", uid).eq("version", version));
            if (flag) af.updateById();
        }
    }


    //积分及时入账
    private void addJifenFlow(User user, BigDecimal money, Boolean ruzhang, Integer fantimeType,
                              String sn, IotypeEnum iotype, JftypeEnum jftype, String remark) {
        Long uid = user.getId();
        Long mid = user.getMid();
        Long mpid = user.getMpid();

        JifenFlow jf = new JifenFlow();
        //*******  客户消耗  *******
        jf.setNum(money);
        jf.setSn(sn);//抵扣积分时 = 订单号
        jf.setIotype(iotype.getVal());//积分消费
        jf.setJftype(jftype.getVal());//积分消费
        jf.setFantimeType(fantimeType);
        jf.setCreatetime(new Date());
        jf.setUid(uid);
        jf.setMid(mid);
        jf.setMpid(mpid);
        jf.setRemark(jftype.getName());
        jf.setIsConfirm(1);
        jf.setConfirmDate(new Date());
        jf.setState(1);
        jf.insert();

        ruzhang = true;//积分及时入账,不在区分支付、核销、7天后入账

        Boolean flag = false;
        while (!flag) {
            Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", uid));
            if (jifen == null) jifen = jifenService.initJifen(uid, mid, mpid);

            long v = jifen.getVersion();
            BigDecimal total = iotype.getVal() == 1 ? jifen.getTotal().add(jf.getNum()) : jifen.getTotal().subtract(jf.getNum());
            BigDecimal fanliing = iotype.getVal() == 1 ? jifen.getFanliing().add(jf.getNum()) : jifen.getFanliing().subtract(jf.getNum());

            if (ruzhang) jifen.setTotal(total);
            else jifen.setFanliing(fanliing);

            jifen.setVersion(jifen.getVersion() + 1);
            jifen.setModifytime(new Date());
            jifen.setModifier(uid);

            flag = jifenService.update(jifen, new EntityWrapper<Jifen>().eq("version", v).eq("uid", uid));
            logger.debug(">>>at jifenService update=" + flag);
        }
    }


    private void addXnbiFlow(User user, BigDecimal money, Boolean ruzhang, Integer fantimeType,
                             String sn, IotypeEnum iotype, XftypeEnum xftype, String remark) {
        Long uid = user.getId();
        Long mid = user.getMid();
        Long mpid = user.getMpid();

        XnbiFlow xflow = new XnbiFlow();
        xflow.setConfirmDate(new Date());
        xflow.setCreatetime(new Date());
        xflow.setIotype(iotype.getVal());
        xflow.setIsConfirm(1);
        xflow.setJftype(xftype.getVal());
        xflow.setFantimeType(fantimeType);//===待实现

        xflow.setUid(uid);
        xflow.setMid(mid);
        xflow.setMpid(mpid);
        xflow.setRemark(remark);
        xflow.setNum(money);
        xflow.setSn(sn);
        xflow.setState(1);
        logger.debug("======xflow=" + xflow);
        xflow.insert();

        ruzhang = true;//及时入账

        Boolean flag = false;
        while (!flag) {
            Xnbi xbi = xnbiService.selectOne(new EntityWrapper<Xnbi>().eq("uid", uid));
            if (xbi == null) xbi = xnbiService.initXnbi(uid, mid, mpid);
            Long version = xbi.getVersion();
            BigDecimal total = xbi.getTotal();
            BigDecimal fanliing = xbi.getFanliing();

            if (ruzhang) xbi.setTotal(iotype.getVal() == 1 ? total.add(money) : total.subtract(money));
            else xbi.setFanliing(iotype.getVal() == 1 ? fanliing.add(money) : fanliing.subtract(money));

            xbi.setModifytime(new Date());
            xbi.setModifier(uid);
            xbi.setVersion(version + 1);
            //******* 更新账户表 ********
            flag = xnbiService.update(xbi, new EntityWrapper<Xnbi>().eq("uid", uid).eq("version", version));
            logger.debug(">>>xnbiService.update flag=" + flag);
        }
    }


    // ====================================  废弃分割线 ====================================

    /*
     * 计算分销额
     * 分销计算原则
     * 1.会员|代理人才有分销权利，普通用户没有
     * 2.普通用户对单个商品分享只能享受商品直推推广分佣（详见方法：shareFan）
     * 3.锁客（锁粉）模式下，上下级关系不变
     * 4.非锁客（锁粉）模式，粉丝变会员之前
     * 5.计算分销额，区别会员商品+普通商品
     * 6.会员商品直接单独购买，不能多商品组合订单
     * 7.普通商品可以组合订单(第一期分销只做总订单分销)
     * 8.第一期分销只做返现金
     * 9.分销价格计算依赖商品实际支付价格
     * 10.上级返佣人，必须是会员才能拥有分佣资格
     */
//    public void fenxiaoFan(Order order) {
//        logger.info("------------------------------------------------------start to come Fenxiao");
//
//        //返现用户
//        User user = null;
//        Long mpid = order.getMpid();
//        Long uid = order.getUid();
//
//        Fenxiao fenxiao = fenxiaoService.selectOne(new EntityWrapper<Fenxiao>().eq("mpid", mpid));
//        MerchantConfig mconfig = redisService.getMconfig(mpid);
//        List<OrderGoods> ogods = orderGoodsService.selectList(new EntityWrapper<OrderGoods>().eq("oid", order.getId()));
//
//        List<FenxiaoFan> fxflist = fenxiaoFanService.selectList(new EntityWrapper<FenxiaoFan>().eq("mpid", mpid).orderBy("mlevel", true));
//
//        if (fenxiao == null) {
//            logger.debug("------------------------------------------------------fenxiao is null for mpid=" + mpid);
//            return;
//        }
//        if (fxflist == null || fxflist.size() == 0) {
//            logger.debug("------------------------------------------------------fxflist is null for mpid=" + mpid);
//            return;
//        }
//
////        if (fxflist.size() != fenxiao.getFxlevel()) {
////            logger.debug("------------------------------------------------------fxflist.size ne fenxiao.getFxlevel for mpid=" + mpid);
////            return;
////        }
//        logger.info("------------------------------------------------------start to come Fenxiao jisuan");
//
//        Map<String, FenxiaoFan> fxmap = new HashMap<String, FenxiaoFan>();
//        for (FenxiaoFan item : fxflist) {
//            fxmap.put("mlevel" + item.getMlevel(), item);
//        }
//        logger.info("------------------------------------------------------start to come Fenxiao fxmap=" + fxmap);
//
//        int fxlevel = fenxiao.getFxlevel();
//        Map<String, User> fxusermap = new HashMap<String, User>();
//        Map<String, BigDecimal> fxemap = new HashMap<String, BigDecimal>();
//        FenxiaoFan fxfan = null;
//        int level = 0;
//
//        BigDecimal jiandian = fenxiao.getJiandian();
//
//        for (int i = 1; i <= fxlevel; i++) {
//            Fens fens = fensService.selectOne(new EntityWrapper<Fens>()
//                    .eq("uid", uid)            //当前成交用户
//                    .eq("level_type", i)      //级别
//                    .eq("status", 2)  //* 10.上级返佣人，必须是会员才能拥有分佣资格
//            );
//
//            if (fens == null) break;
//            user = userService.selectById(fens.getPuid());
//            if (user == null) continue;
//
//            //======待完善
//            //======如果上级会员中途失效，如何处理
//            //======会员升级一般会有见点奖励，特定级别首领有
//            level = user.getMemberLevel();
////           if (user.getIsMember() != 1) break;
//            logger.info("-----------------------------------------------------start to come Fenxiao huiyuan order.getType()=" + order.getType() + " level=" + level);
//
//            String key = "mlevel" + level;
//            logger.info("------------------------------------------------------key=" + key);
//
//            fxfan = fxmap.get(key);//会员对应级别
//            logger.info("---------------------------------------------------------------------------fxfan from fxmap.get(key)=" + fxfan);
//            if (fxfan == null) continue;//非会员 不参与分销
//            logger.info("------------------------------------------------------start to come Fenxiao huiyuan order=" + order);
//
//            if (order.getType() == YXType.hygoods.getVal()) {
//                //会员订单商品，按照会员金额提成（因为升级会员的门槛是固定可控制的）
//                //拉新会员有见点奖励
//                //2  1  1
//                //2  2  1
////               fxfan = fxmap.get("mlevel" + i);
//                //计算分销额
//                if (i == 1) {
//                    order.setFxe1(order.getRealpay().multiply(fxfan.getFan1()).divide(new BigDecimal(100)));
//                    if (fxfan.getIsJiandian() == 1) order.setFxe1(order.getFxe2().add(jiandian));
//                } else if (i == 2) {
//                    order.setFxe2(order.getRealpay().multiply(fxfan.getFan2()).divide(new BigDecimal(100)));
//                    if (fxfan.getIsJiandian() == 1) order.setFxe2(order.getFxe2().add(jiandian));
//                } else if (i == 3) {
//                    order.setFxe3(order.getRealpay().multiply(fxfan.getFan3()).divide(new BigDecimal(100)));
//                    if (fxfan.getIsJiandian() == 1) order.setFxe3(order.getFxe3().add(jiandian));
//                } else if (i == 4) {
//                    order.setFxe4(order.getRealpay().multiply(fxfan.getFan4()).divide(new BigDecimal(100)));
//                    if (fxfan.getIsJiandian() == 1) order.setFxe4(order.getFxe4().add(jiandian));
//                } else if (i == 5) {
//                    order.setFxe5(order.getRealpay().multiply(fxfan.getFan5()).divide(new BigDecimal(100)));
//                    if (fxfan.getIsJiandian() == 1) order.setFxe5(order.getFxe5().add(jiandian));
//                } else if (i == 6) {
//                    order.setFxe6(order.getRealpay().multiply(fxfan.getFan6()).divide(new BigDecimal(100)));
//                    if (fxfan.getIsJiandian() == 1) order.setFxe6(order.getFxe6().add(jiandian));
//                } else if (i == 7) {
//                    order.setFxe7(order.getRealpay().multiply(fxfan.getFan7()).divide(new BigDecimal(100)));
//                    if (fxfan.getIsJiandian() == 1) order.setFxe7(order.getFxe7().add(jiandian));
//                }
//                logger.info("------------------------------------------------------start to over Fenxiao huiyuan order=" + order);
//
//            } else {
//                //非会员商品|普通商品消费，，按照普通商品比例提成
//                logger.info("----------------------------------------------------------------------------------------------------fxfan=" + fxfan);
//                if (i == 1 && fxfan.getXffan1() != null) {
//                    order.setFxe1(order.getRealpay().multiply(BigDecimal.valueOf(fxfan.getXffan1())).divide(new BigDecimal(100)));//实际支付金额*返点比例
////                   if (ogods != null && ogods.size() > 0) {
////                       for (int y = 0; y < ogods.size(); y++) {
////                           OrderGoods ogood = ogods.get(y);
////                           ogood.setFxe1(ogood.getSaleprice().multiply(new BigDecimal(ogood.getNumber())).multiply(BigDecimal.valueOf(fxfan.getXffan1())));
////                       }
////                   }
//                } else if (i == 2 && fxfan.getXffan2() != null) {
//                    order.setFxe2(order.getRealpay().multiply(BigDecimal.valueOf(fxfan.getXffan2())).divide(new BigDecimal(100)));//实际支付金额*返点比例
////                   if (ogods != null && ogods.size() > 0) {
////                       for (int y = 0; y < ogods.size(); y++) {
////                           OrderGoods ogood = ogods.get(y);
////                           ogood.setFxe2(ogood.getSaleprice().multiply(new BigDecimal(ogood.getNumber())).multiply(BigDecimal.valueOf(fxfan.getXffan2())));
////                       }
////                   }
//                } else if (i == 3 && fxfan.getXffan3() != null) {
//                    order.setFxe3(order.getRealpay().multiply(BigDecimal.valueOf(fxfan.getXffan3())).divide(new BigDecimal(100)));//实际支付金额*返点比例
////                   if (ogods != null && ogods.size() > 0) {
////                       for (int y = 0; y < ogods.size(); y++) {
////                           OrderGoods ogood = ogods.get(y);
////                           ogood.setFxe3(ogood.getSaleprice().multiply(new BigDecimal(ogood.getNumber())).multiply(BigDecimal.valueOf(fxfan.getXffan3())));
////                       }
////                   }
//                } else if (i == 4 && fxfan.getXffan4() != null) {
//                    order.setFxe4(order.getRealpay().multiply(BigDecimal.valueOf(fxfan.getXffan4())).divide(new BigDecimal(100)));//实际支付金额*返点比例
////                   if (ogods != null && ogods.size() > 0) {
////                       for (int y = 0; y < ogods.size(); y++) {
////                           OrderGoods ogood = ogods.get(y);
////                           ogood.setFxe4(ogood.getSaleprice().multiply(new BigDecimal(ogood.getNumber())).multiply(BigDecimal.valueOf(fxfan.getXffan4())));
////                       }
////                   }
//                } else if (i == 5 && fxfan.getXffan5() != null) {
//                    order.setFxe5(order.getRealpay().multiply(BigDecimal.valueOf(fxfan.getXffan5())).divide(new BigDecimal(100)));//实际支付金额*返点比例
////                   if (ogods != null && ogods.size() > 0) {
////                       for (int y = 0; y < ogods.size(); y++) {
////                           OrderGoods ogood = ogods.get(y);
////                           ogood.setFxe5(ogood.getSaleprice().multiply(new BigDecimal(ogood.getNumber())).multiply(BigDecimal.valueOf(fxfan.getXffan5())));
////                       }
////                   }
//                } else if (i == 6 && fxfan.getXffan6() != null) {
//                    order.setFxe6(order.getRealpay().multiply(BigDecimal.valueOf(fxfan.getXffan6())).divide(new BigDecimal(100)));//实际支付金额*返点比例
////                   if (ogods != null && ogods.size() > 0) {
////                       for (int y = 0; y < ogods.size(); y++) {
////                           OrderGoods ogood = ogods.get(y);
////                           ogood.setFxe6(ogood.getSaleprice().multiply(new BigDecimal(ogood.getNumber())).multiply(BigDecimal.valueOf(fxfan.getXffan6())));
////                       }
////                   }
//                } else if (i == 7 && fxfan.getXffan7() != null) {
//                    order.setFxe7(order.getRealpay().multiply(BigDecimal.valueOf(fxfan.getXffan7())).divide(new BigDecimal(100)));//实际支付金额*返点比例
////                   if (ogods != null && ogods.size() > 0) {
////                       for (int y = 0; y < ogods.size(); y++) {
////                           OrderGoods ogood = ogods.get(y);
////                           ogood.setFxe7(ogood.getSaleprice().multiply(new BigDecimal(ogood.getNumber())).multiply(BigDecimal.valueOf(fxfan.getXffan7())));
////                       }
////                   }
//                }
//            }
//
//            //被奖励人
//            fxusermap.put("fxuser" + i, user);
//            logger.info("-----------------------------------------------------Fenxiao fxuser=" + user);
//
//            if (i == 1 && order.getFxe1() != null && order.getFxe1().doubleValue() > 0) {
//                fxemap.put("fxe" + i, order.getFxe1());
//            } else if (i == 2 && order.getFxe2() != null && order.getFxe2().doubleValue() > 0)
//                fxemap.put("fxe" + i, order.getFxe2());
//            else if (i == 3 && order.getFxe3() != null && order.getFxe3().doubleValue() > 0)
//                fxemap.put("fxe" + i, order.getFxe3());
//            else if (i == 4 && order.getFxe4() != null && order.getFxe4().doubleValue() > 0)
//                fxemap.put("fxe" + i, order.getFxe4());
//            else if (i == 5 && order.getFxe5() != null && order.getFxe5().doubleValue() > 0)
//                fxemap.put("fxe" + i, order.getFxe5());
//            else if (i == 6 && order.getFxe6() != null && order.getFxe6().doubleValue() > 0)
//                fxemap.put("fxe" + i, order.getFxe6());
//            else if (i == 7 && order.getFxe7() != null && order.getFxe7().doubleValue() > 0)
//                fxemap.put("fxe" + i, order.getFxe7());
//
//        }
//
//        logger.info("---------------------------------------------------start to come Fenxiao 2222");
//
//        if (order.getFantimeType() == null) order.setFantimeType(mconfig.getFantimeType());
//        order.updateById();
//        //===待完善
////       if (ogods != null && ogods.size() > 0) {
////           for (int y = 0; y < ogods.size(); y++) {
////               OrderGoods ogood = ogods.get(y);
////               ogood.updateById();
////           }
////       }
//
//        boolean ruzhang = mconfig.getFantimeType() == FantimeType.payok.getVal();
//        boolean nowfan = mconfig.getIsAutofan() == 1 && ruzhang;
//
//        logger.info("----------------------------------------------------Fenxiao fanyong foreach");
//        for (int i = 1; i <= fenxiao.getFxlevel(); i++) {
//
//            BigDecimal fxe = fxemap.get("fxe" + i);
//            User fxuser = fxusermap.get("fxuser" + i);
//            logger.info("----------------------------------------------------fenxiao fxe=" + fxe);
//            logger.info("----------------------------------------------------fenxiao fxuser=" + fxuser);
//            if (fxuser == null) break;
//
//            fanyong(fxuser, fxe, mconfig.getXffanType(), FantimeType.payok.getVal(), order, ruzhang, nowfan, XftypeEnum.fenxiaofan);
//        }
//
//        logger.info("----------------------------------------------------Fenxiao over");
//    }


}
